package com.wanyangproject.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wanyangproject.R;
import com.wanyangproject.entity.YiKaTongZhiFuEntity;
import com.wanyangproject.my.YiKaTongActivity;
import com.wanyangproject.shouye.ZhiFuActivity;
import com.wanyangproject.utils.ContractUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class YiKaTongZhiFuActivity extends AppCompatActivity {

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.image_zhifubao)
    ImageView imageZhifubao;
    @BindView(R.id.image_weixin)
    ImageView imageWeixin;
    @BindView(R.id.btn_zhifu)
    Button btnZhifu;
    private Boolean panduan = true;   //true为支付宝
    private String money;
    private String state;
    private String water;
    private String id;
    private String name;
    private NetWork netWork;
    private boolean cheng;
    //    IWXAPI是第三方app和微信通信的openapi接口
    public static IWXAPI iwxapi;
    //    微信的APP ID
    private static final String APP_ID_WEChat = "wx363ae6178db5e958";
    private YiKaTongZhiFuEntity yiKaTongZhiFuEntity;
    private static final int SDK_PAY_FLAG = 1;







    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
//                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    String s = msg.obj.toString();
                    String[] split = s.split("\\;");
                    System.out.println(s);

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
//                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
//                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (split[0].contains("9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(YiKaTongZhiFuActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent1=new Intent();
                        intent1.putExtra("chongzhichenggong","chongzhichenggong");
                        intent1.setAction("chongzhichenggong");
                        sendBroadcast(intent1);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(YiKaTongZhiFuActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yi_ka_tong_zhi_fu);
        ButterKnife.bind(this);


        Intent intent = getIntent();
        money = intent.getStringExtra("money");
        state = intent.getStringExtra("state");//1：一卡通2：水费3：电费
        water = intent.getStringExtra("water");//1：冷水2：热水
        id = intent.getStringExtra("id");
        name = intent.getStringExtra("name");


        System.out.println(money+"    金额");
        System.out.println(state+"    充值类型");
        System.out.println(water+"       充值水类型");
        System.out.println(id+"       接收id");
        System.out.println(name+"       接收name");


        if(money.equals("")){

        }else{
            tvMoney.setText(money+"元");
        }




        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("wxpay");
        netWork = new NetWork();
        registerReceiver(netWork, intentFilter);
        imageZhifubao.setImageResource(R.drawable.checked);
        imageWeixin.setImageResource(R.drawable.unchecked);

        //        微信
        regToWx();





    }




    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWork);
    }





    class NetWork extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            cheng = intent.getBooleanExtra("cheng",true);
            if(cheng = true){
                Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
            } else if(cheng = false){
                Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
            }
        }
    }



    //    微信
    private void regToWx() {
        //        通过WXAPOFactory工厂，获取IWXAPI的实例
        iwxapi = WXAPIFactory.createWXAPI(this, APP_ID_WEChat, true);
//        将应用的APP ID注册到微信
        iwxapi.registerApp(APP_ID_WEChat);
    }







    @OnClick({R.id.image_back, R.id.tv_money, R.id.image_zhifubao, R.id.image_weixin, R.id.btn_zhifu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.tv_money:
                break;
//            支付宝
            case R.id.image_zhifubao:
                panduan = true; //支付宝
//                isOK = 0;
                imageZhifubao.setImageResource(R.drawable.checked);
                imageWeixin.setImageResource(R.drawable.unchecked);
                break;
//            微信
            case R.id.image_weixin:
                panduan = false;
//                isOK = 1;
                imageWeixin.setImageResource(R.drawable.checked);
                imageZhifubao.setImageResource(R.drawable.unchecked);
                break;
//            立即支付
            case R.id.btn_zhifu:
//                一卡通充值的网络请求
                initYiKaTongChongZhiHttp();
                break;
        }
    }



//    一卡通充值的网络请求
    private void initYiKaTongChongZhiHttp() {
        if(panduan){//支付宝支付的网络请求
            if(water == null){

                final ProgressDialog progressDialog = new ProgressDialog(YiKaTongZhiFuActivity.this);
                progressDialog.setTitle("提示");
                progressDialog.setMessage("请等待...");
                progressDialog.setCancelable(false);
                progressDialog.show();
                OkHttpUtils.post()
                        .url(ContractUtils.LOGIN_URL+"user/chongzhi")
                        .addHeader("token",ContractUtils.getTOKEN(YiKaTongZhiFuActivity.this))
                        .addParams("parkId",ContractUtils.getParkId(YiKaTongZhiFuActivity.this))
                        .addParams("type","1")//1：支付宝2：微信
                        .addParams("state",state)//1：一卡通2：水费3：电费
                        .addParams("money",money)//金额
                        .addParams("number",id)
                        .addParams("electricityUserName",name)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                System.out.println(e+"        eeeee一卡通支付宝支付的网络请求");
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                System.out.println(response+"          一卡通支付宝支付的网络请求");
                                ContractUtils.Code500(YiKaTongZhiFuActivity.this,response);
                                progressDialog.dismiss();
                                Gson gson = new Gson();
                                yiKaTongZhiFuEntity = gson.fromJson(response, YiKaTongZhiFuEntity.class);
                                System.out.println(yiKaTongZhiFuEntity.getResponse().getSign()+"                     zhiFuEntity.getResponse().getSign()");
                                final String orderInfo = yiKaTongZhiFuEntity.getResponse().getSign();   // 订单信息
//                                    final String orderInfo = "alipay_sdk=alipay-sdk-php-20180705&app_id=2018081761082719&biz_content=%7B%22body%22%3A%22%5Cu4e07%5Cu9633%5Cu5546%5Cu54c1%5Cu652f%5Cu4ed8%22%2C%22subject%22%3A%22%5Cu4e07%5Cu9633%5Cu5546%5Cu54c1%5Cu652f%5Cu4ed8%22%2C%22out_trade_no%22%3A%22pk2sn20180915161517%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A13%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%7D&charset=UTF-8&format=json&method=od=alipay.trade.app.pay&not&notify_url=http%3A%2F%2F%2Fpark.hostop.net%2Fa%2Fapi%2FCallback%2FaliPayBack&sign_type=RSA2&timestamp=2018-09-15+16%3A16%3A40&version=1.0&sign=YlXWgZzSI69B6%2BQQyZSiGp9EAQNDPIBG%2BXUIr8lto9YI9qKK7CVH7P8PAGGfHwPi0p2twj0ad0LEuRafhUC%2BxfTUVxhlMRt3UuH%2Br3cpqjgC6f1KA11YpDwt%2FApO7Z%2BKM1S%2BFcqMCkAu8sfrrEPpuIDNTeDaNyQRefSPeuj%2FuL1WwgKpgX3Os758ip40F5POtoDdmWHr3%2Bj7yXXtqcQiTi63zwsNBWthLq8Z7scVWIqNlGpDXoPYBXaWqBFGOts0UhDGBpcAC7Nd0LjgXeB4gIA5DpDeQKn%2BNqxMjIiZO4JBSZP9O%2F7eN4Bd7eTKkNMqX7V%2FlpMo5IhyLZ%2B7GTQE5g%3D%3D";   // 订单信息


                              Runnable payRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    System.out.println(yiKaTongZhiFuEntity.getResponse().getSign()+"                       System.out.2222222222222222222");
                                    PayTask alipay = new PayTask(YiKaTongZhiFuActivity.this);
                                    String result = alipay.pay(orderInfo,true);
                                    Message msg = new Message();
                                    msg.what = SDK_PAY_FLAG;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            };
                            // 必须异步调用
                            Thread payThread = new Thread(payRunnable);
                            payThread.start();
                            }
                        });
            }else{
                final ProgressDialog progressDialog = new ProgressDialog(YiKaTongZhiFuActivity.this);
                progressDialog.setTitle("提示");
                progressDialog.setMessage("请等待...");
                progressDialog.setCancelable(false);
                progressDialog.show();
                OkHttpUtils.post()
                        .url(ContractUtils.LOGIN_URL+"user/chongzhi")
                        .addHeader("token",ContractUtils.getTOKEN(YiKaTongZhiFuActivity.this))
                        .addParams("parkId",ContractUtils.getParkId(YiKaTongZhiFuActivity.this))
                        .addParams("type","1")//1：支付宝2：微信
                        .addParams("state",state)//1：一卡通2：水费3：电费
                        .addParams("money",money)//金额
                        .addParams("water",water)//1：冷水2：热水
                        .addParams("number",id)
                        .addParams("electricityUserName",name)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                System.out.println(e+"        eeeee一卡通支付宝支付的网络请求");
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                System.out.println(response+"          一卡通支付宝支付的网络请求");
                                ContractUtils.Code500(YiKaTongZhiFuActivity.this,response);
                                progressDialog.dismiss();
                            Gson gson = new Gson();
                            yiKaTongZhiFuEntity = gson.fromJson(response, YiKaTongZhiFuEntity.class);
                            System.out.println(yiKaTongZhiFuEntity.getResponse().getSign()+"                     zhiFuEntity.getResponse().getSign()");
                            final String orderInfo = yiKaTongZhiFuEntity.getResponse().getSign();   // 订单信息
//                                    final String orderInfo = "alipay_sdk=alipay-sdk-php-20180705&app_id=2018081761082719&biz_content=%7B%22body%22%3A%22%5Cu4e07%5Cu9633%5Cu5546%5Cu54c1%5Cu652f%5Cu4ed8%22%2C%22subject%22%3A%22%5Cu4e07%5Cu9633%5Cu5546%5Cu54c1%5Cu652f%5Cu4ed8%22%2C%22out_trade_no%22%3A%22pk2sn20180915161517%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A13%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%7D&charset=UTF-8&format=json&method=od=alipay.trade.app.pay&not&notify_url=http%3A%2F%2F%2Fpark.hostop.net%2Fa%2Fapi%2FCallback%2FaliPayBack&sign_type=RSA2&timestamp=2018-09-15+16%3A16%3A40&version=1.0&sign=YlXWgZzSI69B6%2BQQyZSiGp9EAQNDPIBG%2BXUIr8lto9YI9qKK7CVH7P8PAGGfHwPi0p2twj0ad0LEuRafhUC%2BxfTUVxhlMRt3UuH%2Br3cpqjgC6f1KA11YpDwt%2FApO7Z%2BKM1S%2BFcqMCkAu8sfrrEPpuIDNTeDaNyQRefSPeuj%2FuL1WwgKpgX3Os758ip40F5POtoDdmWHr3%2Bj7yXXtqcQiTi63zwsNBWthLq8Z7scVWIqNlGpDXoPYBXaWqBFGOts0UhDGBpcAC7Nd0LjgXeB4gIA5DpDeQKn%2BNqxMjIiZO4JBSZP9O%2F7eN4Bd7eTKkNMqX7V%2FlpMo5IhyLZ%2B7GTQE5g%3D%3D";   // 订单信息


                            Runnable payRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    System.out.println(yiKaTongZhiFuEntity.getResponse().getSign()+"                       System.out.2222222222222222222");
                                    PayTask alipay = new PayTask(YiKaTongZhiFuActivity.this);
                                    String result = alipay.pay(orderInfo,true);
                                    Message msg = new Message();
                                    msg.what = SDK_PAY_FLAG;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            };
                            // 必须异步调用
                            Thread payThread = new Thread(payRunnable);
                            payThread.start();
                            }
                        });
            }
        }else{//微信支付的网络请求
            if(water == null){
                final ProgressDialog progressDialog = new ProgressDialog(YiKaTongZhiFuActivity.this);
                progressDialog.setTitle("提示");
                progressDialog.setMessage("请等待...");
                progressDialog.setCancelable(false);
                progressDialog.show();
                OkHttpUtils.post()
                        .url(ContractUtils.LOGIN_URL+"user/chongzhi")
                        .addHeader("token",ContractUtils.getTOKEN(YiKaTongZhiFuActivity.this))
                        .addParams("parkId",ContractUtils.getParkId(YiKaTongZhiFuActivity.this))
                        .addParams("type","2")//1：支付宝2：微信
                        .addParams("state",state)//1：一卡通2：水费3：电费
                        .addParams("money",money)//金额
                        .addParams("number",id)
                        .addParams("electricityUserName",name)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                System.out.println(e+"            eeeee一卡通微信支付的网络请求");
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                System.out.println(response+"           一卡通微信支付的网络请求");
                                progressDialog.dismiss();
                            if(response.indexOf("200") != -1){
                                Gson gson = new Gson();
                                yiKaTongZhiFuEntity = gson.fromJson(response, YiKaTongZhiFuEntity.class);
                                IWXAPI api;
                                PayReq request = new PayReq();
                                request.appId = yiKaTongZhiFuEntity.getResponse().getAppid();
                                request.partnerId = yiKaTongZhiFuEntity.getResponse().getPartnerid();
                                request.prepayId= yiKaTongZhiFuEntity.getResponse().getPrepayid();
                                request.packageValue = yiKaTongZhiFuEntity.getResponse().getPackageX();
                                request.nonceStr= yiKaTongZhiFuEntity.getResponse().getNoncestr();
                                request.timeStamp= yiKaTongZhiFuEntity.getResponse().getTimestamp();
                                request.sign= yiKaTongZhiFuEntity.getResponse().getSign();
                                iwxapi.sendReq(request);
                                finish();
                            }
                            }
                        });

            }else {
                final ProgressDialog progressDialog = new ProgressDialog(YiKaTongZhiFuActivity.this);
                progressDialog.setTitle("提示");
                progressDialog.setMessage("请等待...");
                progressDialog.setCancelable(false);
                progressDialog.show();
                OkHttpUtils.post()
                        .url(ContractUtils.LOGIN_URL+"user/chongzhi")
                        .addHeader("token",ContractUtils.getTOKEN(YiKaTongZhiFuActivity.this))
                        .addParams("parkId",ContractUtils.getParkId(YiKaTongZhiFuActivity.this))
                        .addParams("type","2")//1：支付宝2：微信
                        .addParams("state",state)//1：一卡通2：水费3：电费
                        .addParams("money",money)//金额
                        .addParams("water",water)//1：冷水2：热水
                        .addParams("number",id)
                        .addParams("electricityUserName",name)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                System.out.println(e+"            eeeee一卡通微信支付的网络请求");
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                System.out.println(response+"           一卡通微信支付的网络请求");
                                progressDialog.dismiss();
                            if(response.indexOf("200") != -1){
                                Gson gson = new Gson();
                                yiKaTongZhiFuEntity = gson.fromJson(response, YiKaTongZhiFuEntity.class);
                                IWXAPI api;
                                PayReq request = new PayReq();
                                request.appId = yiKaTongZhiFuEntity.getResponse().getAppid();
                                request.partnerId = yiKaTongZhiFuEntity.getResponse().getPartnerid();
                                request.prepayId= yiKaTongZhiFuEntity.getResponse().getPrepayid();
                                request.packageValue = yiKaTongZhiFuEntity.getResponse().getPackageX();
                                request.nonceStr= yiKaTongZhiFuEntity.getResponse().getNoncestr();
                                request.timeStamp= yiKaTongZhiFuEntity.getResponse().getTimestamp();
                                request.sign= yiKaTongZhiFuEntity.getResponse().getSign();
                                iwxapi.sendReq(request);
                                finish();
                            }
                            }
                        });
            }

        }
    }
}
